package jvm;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStream;

/**
 * 自定义类加载器
 * 
 * @author fidel
 */
public class CustomClassLoader extends ClassLoader {
    @Override
    protected Class<?> findClass(String name) throws ClassNotFoundException {
        try (InputStream ios = new FileInputStream(name);) {
            // 读取输入流的所有字节
            byte[] classBytes = ios.readAllBytes();
            if (classBytes == null) {
                throw new FileNotFoundException();
            } else {
                name = getClass().getName();
                // 将一个字节数组转换为Class的实例。在使用Class之前，必须先对其进行解析
                return defineClass(name, classBytes, 0, classBytes.length);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
